package com.example.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.blog.dto.UserDTO;
import com.example.blog.entity.User;
import com.example.blog.lang.Result;
import com.example.blog.mapper.UserMapper;
import com.example.blog.service.UserService;
import com.example.blog.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author anonymous
 * @since 2021-12-15
 */
@CrossOrigin
@RestController
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody UserDTO userDTO, HttpServletResponse response, HttpSession session){
        log.info("user：{},{}",userDTO.getUsername(),userDTO.getPassword());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",userDTO.getUsername());
        User user = userMapper.selectOne(wrapper);
        Result<UserVO> userResult = new Result<>();
        if (user==null){
            userResult.fail("400","用户不存在");
        }
        String password = DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes());
        if (!user.getPassword().equals(password)){
            userResult.fail("410","密码错误");
        }else{
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            String token = UUID.randomUUID().toString();
            userVO.setToken(token);
            session.setAttribute("token",token);
            userResult.succ("操作成功",userVO);
        }
        return userResult;
    }

    @GetMapping("/logout")
    public Result<User> logout(HttpSession session){
        session.invalidate();
        Result<User> result = new Result<>();
        result.succ("操作成功",null);
        return result;
    }
}
